package pers.xuehongyan.useat.server.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pers.xuehongyan.useat.server.enity.User;
import pers.xuehongyan.useat.server.exception.ServiceException;
import pers.xuehongyan.useat.server.service.UserService;

import javax.annotation.Resource;

/**
 * @author xuehongyan
 */
@RestController
@CrossOrigin(origins = {"*", "null"})
@RequestMapping("/auth")
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/register")
    public ResponseEntity<Void> register(@RequestParam("username") String username, @RequestParam("password") String rawPassword) {
        userService.register(username, rawPassword);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestParam("username") String username, @RequestParam("password") String rawPassword) {
        try {
            return ResponseEntity.ok(userService.login(username, rawPassword));
        } catch (ServiceException e) {
            return ResponseEntity.status(e.getHttpStatus()).build();
        }
    }

    @GetMapping("/")
    public ResponseEntity<User> profile(@RequestParam("token") String token) {
        try {
            return ResponseEntity.ok(userService.getUserByToken(token));
        } catch (ServiceException e) {
            return ResponseEntity.status(e.getHttpStatus()).build();
        }
    }
}
